<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 执行状态
interface ExecutionStatus {
  status: 'idle' | 'running' | 'completed' | 'error'
  output: string
}

const status = ref<ExecutionStatus>({
  status: 'idle',
  output: ''
})

const scriptPath = '/Users/yuxl/span/ali/cloud-galaxy/a.sh'

// 格式化输出
const formatOutput = (text: string) => {
  // 替换 [INFO], [WARNING], [ERROR] 等标签为带颜色的版本
  return text
    .replace(/\[INFO\]/g, '&lt;span style="color: #67C23A">[INFO]&lt;/span>')
    .replace(/\[WARNING\]/g, '&lt;span style="color: #E6A23C">[WARNING]&lt;/span>')
    .replace(/\[ERROR\]/g, '&lt;span style="color: #F56C6C">[ERROR]&lt;/span>')
    .replace(/\[DEBUG\]/g, '&lt;span style="color: #909399">[DEBUG]&lt;/span>')
    .replace(/\[SUCCESS\]/g, '&lt;span style="color: #67C23A">[SUCCESS]&lt;/span>')
    .replace(/FAILURE/g, '&lt;span style="color: #F56C6C">FAILURE&lt;/span>')
    .replace(/SKIPPED/g, '&lt;span style="color: #909399">SKIPPED&lt;/span>')
    .replace(/BUILD FAILURE/g, '&lt;span style="color: #F56C6C">BUILD FAILURE&lt;/span>')
    .replace(/BUILD SUCCESS/g, '&lt;span style="color: #67C23A">BUILD SUCCESS&lt;/span>')
}

// 处理进程输出
const handleProcessOutput = (output: { type: 'stdout' | 'stderr'; data: string }) => {
  console.log('[DEBUG] 收到输出:', output)
  if (output && output.data) {
    // 根据输出类型处理
    const formattedOutput = formatOutput(output.data)
    if (output.type === 'stderr') {
      console.log('[DEBUG] 错误输出:', output.data)
      status.value.output += `&lt;span class="error">${formattedOutput}&lt;/span>`
    } else {
      console.log('[DEBUG] 标准输出:', output.data)
      status.value.output += formattedOutput
    }
    // 自动滚动到底部
    const outputElement = document.querySelector('.output-content')
    if (outputElement) {
      setTimeout(() => {
        outputElement.scrollTop = outputElement.scrollHeight
      }, 0)
    }
  }
}

// 在组件挂载时注册输出回调
onMounted(() => {
  window.childProcess.onOutput(handleProcessOutput)
})

// 在组件卸载时移除输出回调
onUnmounted(() => {
  window.childProcess.offOutput()
})

// 执行脚本
const handleExecute = async () => {
  try {
    console.log('[DEBUG] 开始执行脚本')
    // 重置状态
    status.value = {
      status: 'running',
      output: ''
    }

    // 添加初始志
    status.value.output += formatOutput(`[INFO] 开始执行脚本: ${scriptPath}\n`)
    
    // 检查脚本是否存在
    console.log('[DEBUG] 检查脚本是否存在:', scriptPath)
    const existsResult = await window.fs.existsSync(scriptPath)
    console.log('[DEBUG] 脚本存在状态:', existsResult)
    
    if (!existsResult.success) {
      throw new Error(`检查文件失败: ${existsResult.error}`)
    }
    
    if (!existsResult.data) {
      throw new Error(`脚本文件不存在: ${scriptPath}`)
    }
    
    // 执行命令
    const workDir = scriptPath.substring(0, scriptPath.lastIndexOf('/'))
    console.log('[DEBUG] 工作目录:', workDir)
    console.log('[DEBUG] 准备执行命令: bash', scriptPath)
    
    const result = await window.childProcess.exec(`bash "${scriptPath}"`, {
      cwd: workDir
    })

    console.log('[DEBUG] 命令执行完成，结果:', JSON.stringify(result))

    // 如果有stdout或stderr，显示出来
    if (result.stdout && !status.value.output.includes(result.stdout)) {
      status.value.output += formatOutput(result.stdout)
    }
    if (result.stderr && !status.value.output.includes(result.stderr)) {
      status.value.output += `<span class="error">${formatOutput(result.stderr)}</span>`
    }

    // 添加执行结果日志
    status.value.output += formatOutput(`\n[INFO] 脚本执行完成\n`)
    
    // 更新状态
    const exitCode = result?.code ?? null
    console.log('[DEBUG] 退出码:', exitCode)
    
    if (exitCode !== null) {
      status.value.output += formatOutput(`[INFO] 退出码: ${exitCode}\n`)
      
      // 根据退出码设置状态
      status.value.status = exitCode === 0 ? 'completed' : 'error'
      if (exitCode === 0) {
        console.log('[DEBUG] 脚本执行成功')
        status.value.output += formatOutput(`\n[SUCCESS] 脚本执行成功\n`)
      } else {
        console.log('[DEBUG] 脚本执行失败，退出码:', exitCode)
        status.value.output += formatOutput(`\n[ERROR] 脚本执行失败，退出码: ${exitCode}\n`)
      }
    } else {
      console.log('[DEBUG] 无法获取退出码:', JSON.stringify(result))
      status.value.status = 'error'
      status.value.output += formatOutput(`[INFO] 退出码: undefined\n`)
      status.value.output += formatOutput(`\n[ERROR] 无法获取脚本执行结果\n`)
    }
    
  } catch (error) {
    console.error('[DEBUG] 执行脚本失败:', error)
    status.value.status = 'error'
    status.value.output += formatOutput(`\n[ERROR] 执行失败: ${error instanceof Error ? error.message : String(error)}\n`)
  }
}
</script>

<template>
  <div class="test-container">
    <div class="control-panel">
      <el-button type="primary" @click="handleExecute" :loading="status.status === 'running'">
        执行脚本
      </el-button>
      <div class="status-light" :class="status.status"></div>
    </div>
    
    <div class="output-panel">
      <div class="output-header">
        <span>执行输出</span>
        <el-tag :type="status.status === 'completed' ? 'success' : status.status === 'error' ? 'danger' : status.status === 'running' ? 'warning' : 'info'">
          {{ status.status === 'idle' ? '未执行' : 
             status.status === 'running' ? '执行中' :
             status.status === 'completed' ? '执行完成' : '执行出错' }}
        </el-tag>
      </div>
      <div class="output-content" v-html="status.output.replace(/\n/g, '&lt;br>')"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.test-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.control-panel {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-light {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #909399;
  transition: background-color 0.3s;

  &.running {
    background-color: #F56C6C;
    animation: blink 1s infinite;
  }

  &.completed {
    background-color: #67C23A;
  }

  &.error {
    background-color: #F56C6C;
  }
}

.output-panel {
  flex: 1;
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.output-header {
  padding: 10px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.output-content {
  flex: 1;
  padding: 10px;
  font-family: monospace;
  white-space: pre-wrap;
  overflow-y: auto;
  background: var(--el-bg-color-page);
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.5;
  max-height: calc(100vh - 200px); /* 限制最大高度 */

  :deep(.error) {
    color: #F56C6C;
  }
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>

